import API from "@/API";
import ETable from '@/components/ETable'
// 子组件
import PermForm from '@/components/permission/PermForm'
import RoleForm from '@/components/permission/RoleForm'
import UserAuthForm from '@/components/permission/UserAuthForm';
import Utils from "@/utils/utils";
import { Button, Card, Modal } from 'antd';
import React, { Component } from 'react';
import { IParams,IProps,IState } from "./types";

export default class PermissionUser extends Component<IProps,IState> {

  public state:IState;
  public params:IParams;
  public roleForm:any;
  public permForm: any;
  public userAuthForm:any;
  constructor(props: Readonly<IProps>) {
    super(props)
    this.state = {
      isRoleVisible: false, // 控制创建用户显示隐藏
      isPermVisible: false, // 控制设置权限显示隐藏
      isUserVisible: false, // 控制用户授权显示隐藏
      detailInfo: {}, // 选中的数据，传入给子组件
      menuInfo: [], // 权限选中数组
      selectedItem:{
        id:0,
        menus:null
      },
      list:[],
      pagination:{}
    }
    this.params = {
      id: 1
    }
  }
  /**
   * 页面一进入就请求获取API
   */
  public componentDidMount() {
    this.requestList()
  }

  /**
   * 请求函数
   */
  public requestList = () => {
    // 调用公共封装的列表请求函数
    API.getRoleList(this, {}, true)
  }

  /**
   * 点击创建用户
   */
  public handleClearContent = () => {
    this.setState({
      isRoleVisible: true
    })
  }

  /**
   * 设置权限
   */
  public handlePermission = () => {
    const item = this.state.selectedItem;
    if (Object.keys(item).length < 1) {
      Modal.info({
        title: '信息',
        content: '请选择一个角色'
      })
      return;
    }
    this.setState({
      isPermVisible: true,
      detailInfo: item,
      menuInfo: item.menus
    })
  }

  /**
   * 用户授权
   */
  public handleUserAuth = () => {
   const item = this.state.selectedItem;
    if (Object.keys(item).length < 1) {
      Modal.info({
        title: '信息',
        content: '未选中任何项目'
      })
      return;
    }
    // 调用请求用户数据
    this.getRoleUserList(this.state.selectedItem.id);
    this.setState({
      isUserVisible: true,
      detailInfo: this.state.selectedItem // 赋值选中的数据
    })
  }

  /**
   * 请求权限用户数据数据
   * @param {Number} id 选择类别的id
   */
  public getRoleUserList = (id:number) => {
    API.getRoleUserList({
      data: {
        params: {
          id
        }
      },
      isMock: true
    }).then((res:any) => {
      if (res) {
        // 调用构建穿梭框的数据
        this.getAuthUserList(res.result);
      }
    })
  }

  /**
   * 筛选目标用户
   * @param {array} dataSource 请求回来的用户数据
   */
  public getAuthUserList = (dataSource:any[]) => {
    const mockData = [];
    const targetKeys = [];
    if (dataSource && dataSource.length > 0) {
      for (const dataSources of dataSource) {
        const data = {
          key: dataSources.user_id,
          title: dataSources.user_name,
          status: dataSources.status,
        };
        if (data.status == 1) {
          targetKeys.push(data.key);
        }
        mockData.push(data);
      }
    }
    this.setState({ mockData, targetKeys });
  };

  /**
   * 子组件
   */
  public handleRoleSubmit = () => {
    // 调用验证
    this.roleForm.props.form.validateFields((err:any) => {
      // 通过验证执行
      if (!err) {
        // 获取表单数据
        const data = this.roleForm.props.form.getFieldsValue();
        API.getRoleCreate({
          data: {
            params: data
          },
          isMock: true
        }).then((res:any) => {
          if (res.code == 0) {
            this.setState({
              isRoleVisible: false // 关闭弹框
            })
            this.roleForm.props.form.resetFields() // 重置表单
            this.requestList()
          }
        })
      }
    });
  }

  /**
   * 权限控制提交
   */
  public handlePermSubmit = () => {
    const data = this.permForm.props.form.getFieldsValue();
    // 获取当前选中的数据id
    data.role_id = this.state.selectedItem.id;
    // 获取赋值权限选中数据
    data.menus = this.state.menuInfo;
    API.getPermissionEdit({
      data: {
        params: {
          ...data
        }
      },
      isMock: true
    }).then((res:any) => {
      this.setState({
        isPermVisible: false
      })
      this.permForm.props.form.resetFields()
      this.requestList()
    })
  }

  /**
   * 用户授权
   */
  public handleUserAuthSubmit = () => {
    const data:{user_ids?:any,role_id?:any} = {};
    data.user_ids = this.state.targetKeys || [];
    data.role_id = this.state.selectedItem.id;
    API.getRoleUserEdit({
      data: {
        params: {
          ...data
        }
      },
      isMock: true
    }).then((res:any) => {
      if (res) {
        this.setState({
          isUserVisible: false
        })
        this.requestList();
      }
    })
  }

  /**
   * 记录子组件穿梭框右侧保留的数据
   */
  public patchUserInfo = (targetKeys:any) => {
    this.setState({
      targetKeys
    });
  };

  public updateSelectedItem = (selectedRowKeys: any, selectedRows: any, selectedIds?: any) => {
    if (selectedIds) {
      this.setState({
        selectedRowKeys,
        selectedIds,
        selectedItem: selectedRows
      })
    } else {
      this.setState({
        selectedRowKeys,
        selectedItem: selectedRows
      })
    }
  }

  public render() {

    const columns = [
      {
        title: '角色ID',
        dataIndex: 'id'
      },
      {
        title: '角色名称',
        dataIndex: 'role_name'
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        render: Utils.formateDate,
        width: 200
      },
      {
        title: '使用状态',
        dataIndex: 'status',
        render(status:number) {
          return status == 1 ? '启用' : '禁用'
        }
      },
      {
        title: '授权时间',
        dataIndex: 'authorize_time',
        render: Utils.formateDate,
        width: 200
      },
      {
        title: '授权人',
        dataIndex: 'authorize_user_name'
      },
    ]

    return (
      <div>
        <Card>
          <Button type="primary" onClick={ this.handleClearContent }>创建角色</Button>
          <Button type="primary" onClick={ this.handlePermission }>设置权限</Button>
          <Button type="primary" onClick={ this.handleUserAuth }>用户授权</Button>
        </Card>
        <div className="content-wrap">
          <ETable
            updateSelectedItem={ this.updateSelectedItem }
            selectedRowKeys={ this.state.selectedRowKeys }
            dataSource={ this.state.list }
            columns={ columns }
            pagination={ this.state.pagination } />
        </div>
        <Modal
          title="创建角色"
          visible={ this.state.isRoleVisible }
          onOk={ this.handleRoleSubmit }
          onCancel={ () => {
            this.roleForm.props.form.resetFields()
            this.setState({
              isRoleVisible: false
            })
          } }>
          <RoleForm wrappedComponentRef={ (inst: any ) => this.roleForm = inst } />
        </Modal>
        <Modal
          title="控制权限"
          visible={ this.state.isPermVisible }
          width={ 600 }
          onOk={ this.handlePermSubmit }
          onCancel={ () => {
            this.permForm.props.form.resetFields()
            this.setState({
              isPermVisible: false
            })
          } }>
          <PermForm
            detailInfo={ this.state.detailInfo }
            menuInfo={ this.state.menuInfo }
            patchMenuInfo={ (checkedKeys: any) => {
              this.setState({
                menuInfo: checkedKeys
              })
            } }
            wrappedComponentRef={ (inst: any) => this.permForm = inst } />
        </Modal>
        <Modal
          title="用户授权"
          width={800}
          visible={ this.state.isUserVisible }
          onOk={ this.handleUserAuthSubmit }
          onCancel={ () => {
            this.userAuthForm.props.form.resetFields()
            this.setState({
              isUserVisible: false
            })
          } }>
          <UserAuthForm
            wrappedComponentRef={ (inst: any) => this.userAuthForm = inst }
            detailInfo={ this.state.detailInfo }
            targetKeys={ this.state.targetKeys }
            mockData={ this.state.mockData }
            patchUserInfo={ this.patchUserInfo } />
        </Modal>
      </div>
    )
  }
}
